package client.view;

import java.awt.Component;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

import net.GameInfo;
import client.LobbyClient;

/**
 * Displays a list of tables available on the MasterServer.
 */
public class TableList extends JList {
	private DefaultListModel dlm;
	private LobbyClient client;

	/**
	 * Creates a new TableList for the given LobbyClient
	 */
	public TableList(LobbyClient c) {
		dlm = new DefaultListModel();
		this.setModel(dlm);
		this.setCellRenderer(new TableListRenderer());
		this.client = c;
		for (GameInfo g : c.getTables()) {
			addTable(g);
		}
	}

	/**
	 * Adds a new TableView for the given GameInfo to the list of tables
	 * available
	 */
	public void addTable(GameInfo g) {
		dlm.addElement(new TableView(g));
		if (dlm.getSize()>0) this.setSelectedIndex(0);
	}

	/**
	 * Removes the TableView from the list of tables available
	 */
	public void removeTable(GameInfo g) {
		for (int i = 0; i < dlm.getSize(); i++) {
			TableView tv = (TableView) (dlm.getElementAt(i));
			if (tv.getGameInfo().equals(g)) { dlm.removeElement(tv); }
		}
		if (dlm.getSize()>0) this.setSelectedIndex(0);
	}

	/**
	 * Retrieves the selected TableView in the list
	 */
	public TableView getSelectedTableView() {
		return (TableView) (this.getSelectedValue());
	}

	private class TableListRenderer implements ListCellRenderer {
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean hasFocus) {
			TableView tv = (TableView) value;
			if (isSelected) {
				tv.setBackground(list.getSelectionBackground());
				tv.setForeground(list.getSelectionForeground());
			} else {
				tv.setBackground(list.getBackground());
				tv.setForeground(list.getForeground());
			}
			return tv;
		}
	}
}
